package com.kzj.mls.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.webkit.JavascriptInterface;

import com.kzj.mls.R;
import com.kzj.mls.beans.CloseActivityBean;
import com.kzj.mls.beans.OrderBean;
import com.kzj.mls.fragment.OrderFragment;
import com.kzj.mls.global.App;
import com.kzj.mls.global.Constant;
import com.kzj.mls.html5.Html5Webview;
import com.kzj.mls.recyclerCard.cardView.ServiceOrderCardView;
import com.kzj.mls.request.BaseResponse;
import com.kzj.mls.request.ICallBackForRequestServer;
import com.kzj.mls.request.RequestServerManager;
import com.kzj.mls.widget.dialog.SweetDialogManager;
import com.kzj.mls.wxapi.WXPayEntryActivity;
import com.umeng.analytics.MobclickAgent;

import java.util.Timer;
import java.util.TimerTask;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;
import de.greenrobot.event.EventBus;

/**
 * 公用H5 访问页
 *
 * @author boom
 */
@SuppressLint("NewApi")
public class OrderWebActivity extends GBaseActivity {

    Html5Webview mWebView;
    public static final String WebUrl = "WebUrl";
    public static final String Title = "Title";
    public static final String RightTest = "RightText";
    public static final String IsNeedShare = "isNeedShare";// 转发用
    public static final String NoEdit = "NoEdit";// 禁止编辑
    public static final String upLoadPreviewHtml5 = "upLoadPreviewHtml5";// 预览完成upLoadPreviewHtml5用
    public static final String activityID = "activityID";// 预览完成upLoadPreviewHtml5用,更改活动ID
    public static final String IsCoolAct = "IsCoolAct";// IsCoolAct
    public static final String IsBrandTrain = "IsBrandTrain";// IsCoolAct
    private boolean isCoolAct;
    private boolean isBrandTrain;
    public String isNeedShare;
    public String noEdit;
    public String activityId;
    protected String url;
    private boolean isTaskDoing = false;

    private OrderBean orderBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebView = new Html5Webview(this);
        String title = getIntent().getStringExtra(Title);
        String weburl = getIntent().getStringExtra(WebUrl);
        isCoolAct = getIntent().getBooleanExtra(IsCoolAct, false);
        isBrandTrain = getIntent().getBooleanExtra(IsBrandTrain, false);
        activityId = getIntent().getStringExtra(activityID);
        isNeedShare = getIntent().getStringExtra(IsNeedShare);
        noEdit = getIntent().getStringExtra(NoEdit);
        orderBean = (OrderBean) getIntent().getSerializableExtra("order_bean");
        if (!TextUtils.isEmpty(weburl)) {
            url = weburl + "&user_checked=" + App.getInstance().getUserBean().getUser_checked();
        }
        setTopTitle(title);

        setLeftImg(View.VISIBLE, R.drawable.selector_back);

        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        } else {
            if (url != null) {

                mWebView.loadUrl(url);

            }
        }
        setContentView(mWebView.getLayout());
        mWebView.addJavascriptInterface(new CallJs(), "robot");
        EventBus.getDefault().register(this);
    }

    public class CallJs {
        @JavascriptInterface
        public void callServiceOrder(final String sid, String city, String lng, String lat) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (App.getInstance().getUserBean() != null) {
                        Intent intent = new Intent(OrderWebActivity.this, ServiceOrderActivity.class);
                        intent.putExtra(ServiceOrderActivity.TagSID, sid);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(OrderWebActivity.this, LoginActivity.class);
                        intent.putExtra("activity", "service");
                        startActivity(intent);
                    }

                }
            });
        }


        @JavascriptInterface
        public void payOrder(String id, String payment_code) {
            if (payment_code.equals(ServiceOrderCardView.payTypeAlipay)) {

            } else {

            }
        }

        @JavascriptInterface
        public void getTitle(final String titleTemp) {
            runOnUiThread(new Runnable() {
                public void run() {
                    setTopTitle(titleTemp);

                }
            });

        }

        @JavascriptInterface
        public void cancelOrder(final String id) {
            if (orderBean != null) {
                if (orderBean.getStatus() == null) {
                    SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "取消订单",
                            "确定取消订单吗？", true, true, new OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                }
                            }, new OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    TaskCancleOrder(id);
                                }
                            });
                } else {
                    if (orderBean.getStatus().equals("11")) {
                        SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "取消订单",
                                "确定取消订单吗？", true, true, new OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                    }
                                }, new OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        TaskCancleOrder(id);
                                    }
                                });
                    } else {
                        SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "是否取消订单？",
                                "若取消订单，所支付款项将被返回到您的支付账户。", true, true, new OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                    }
                                }, new OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        TaskCancleOrder(id);
                                    }
                                });
                    }
                }
            }
        }

        @JavascriptInterface
        public void delOrder(final String id) {
            SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity) getActivity(), "删除订单",
                    "确定删除订单吗？", true, true, new OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    }, new OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            TaskDeleteOrder(id);
                        }
                    });
        }

    }

    @Override
    protected void findViewByIds() {

    }

    @Override
    protected void initDatas() {

    }

    @Override
    protected void fillArrayInListView() {

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }

    }

    private void TaskDeleteOrder(String order_id) {
        RequestServerManager.getInstance().handleMethod(OrderWebActivity.this, null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Delete_Order, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Delete_Order, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        App.getInstance().showToast("订单删除成功！");
                        EventBus.getDefault().post(new CloseActivityBean());
                        OrderWebActivity.this.finish();
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    private void TaskCancleOrder(String order_id) {
        RequestServerManager.getInstance().handleMethod(OrderWebActivity.this, null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Cancle_Order, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Cancle_Order, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        App.getInstance().showToast("订单取消成功！");
                        EventBus.getDefault().post(new CloseActivityBean());
                        OrderWebActivity.this.finish();
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {

        if (mWebView != null && mWebView.getSettings() != null) {//解决Receiver not registered: android.widget.ZoomButtonsController
            mWebView.getSettings().setBuiltInZoomControls(true);
            mWebView.setVisibility(View.GONE);// 把destroy()延后
            long timeout = ViewConfiguration.getZoomControlsTimeout();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            mWebView.removeAllViews();
                            mWebView.destroy();
                        }
                    });

                }
            }, timeout);
        }

        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.inCustomView()) {
                mWebView.hideCustomView();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    public void onEventMainThread(CloseActivityBean closeActivityBean) {
        if (closeActivityBean.isSuccess()) {
            finish();
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
        MobclickAgent.onResume(this);          //统计时长
    }
}